import React, { useState, useEffect } from "react";
import { Button, Space, Table, Tag, message, Popconfirm } from "antd";
import { PlusOutlined, MinusOutlined } from "@ant-design/icons";
import { useTranslation } from "react-i18next";
import { ItagType } from "@/types/type";
import AddTag from "./AddTagForm";
import type { TableColumnsType, TableProps } from "antd";
import {
  getTag,
  addTag,
  editTag,
  deleteTag,
  deleteTags,
} from "@/service/myrequest";
type TableRowSelection<T> = TableProps<T>["rowSelection"];

const LabelPage: React.FC = () => {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [dialog, setDialog] = useState("");
  const [currentTag, setCurrentTag] = useState<ItagType>();
  const [tagdata, setTagdata] = useState<ItagType[]>([]);
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (value: React.Key[]) => {
    setselectedRowKeys(value);
  };

  //列表列配置
  const columns: TableColumnsType<ItagType> = [
    {
      title: t("table.tag"),
      key: "id",
      width: "50%",
      render: (record: ItagType) => (
        <Tag color={record.color}>{record.name}</Tag>
      ),
    },
    {
      title: t("table.action"),
      render: (record: ItagType) => (
        <Space size="large">
          <a style={{ color: "#1677FF" }} onClick={() => showEditModal(record)}>
            {t("table.edit")}
          </a>
          <Popconfirm
            okText={t("confirm")}
            cancelText={t("cancel")}
            title={t("deltxt")}
            onConfirm={() => {
              handleDeleteTag(record.id);
            }}
          >
            <a style={{ color: "#FF4D4F" }}>{t("table.delete")}</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  //标签多选
  const rowSelection: TableRowSelection<ItagType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  useEffect(() => {
    getTags();
  }, []);

  //查询
  const getTags = () => {
    getTag().then(tags => {
      setTagdata(tags);
    });
  };

  //显示添加弹窗
  const showAddModal = () => {
    setDialog("AddTag");
    setOpen(true);
  };

  //显示编辑弹窗
  const showEditModal = (item: ItagType) => {
    setCurrentTag(item);
    setDialog("EditTag");
    setOpen(true);
  };

  //添加标签
  const handleAddTag = (value: ItagType) => {
    addTag(value)
      .then(() => {
        message.success(t("addsu"));
        getTags();
      })
      .catch(err => {
        message.error(t("addfa") + err.data.msg);
      });
    setOpen(false);
  };

  //编辑标签
  const handleEditTag = (updata: ItagType) => {
    editTag(updata)
      .then(() => {
        message.success(t("editsu"));
        getTags();
      })
      .catch(err => message.error(t("editfa") + err.data.msg));
    setOpen(false);
  };

  //删除标签
  const handleDeleteTag = (taginfo: string) => {
    deleteTag(taginfo)
      .then(() => {
        message.success(t("delsu"));
        getTags();
      })
      .catch((err: any) => message.error(err.data.msg));
  };

  //批量删除标签
  const handleDeleteTags = () => {
    deleteTags(selectedRowKeys)
      .then((res: any) => {
        message.success(res.msg);
        if (res.data.length !== 0) {
          message.warning(res.data + t("tagsused"));
        }
        getTags();
        setselectedRowKeys([]);
      })
      .catch(err => message.error(err.data.msg));
  };

  //取消弹窗
  const handleClose = () => {
    setOpen(false);
  };
  return (
    <div className="my-tag-bac">
      <div className="my-tagbac-tool">
        <Space>
          {/* 添加标签按钮 */}
          <Button type="primary" onClick={showAddModal}>
            <PlusOutlined />
            {t("table.addtag")}
          </Button>

          {/* 批量删除按钮 */}
          <Button
            type="primary"
            danger
            disabled={selectedRowKeys.length === 0}
            onClick={handleDeleteTags}
          >
            <MinusOutlined />
            {t("confirmdelete")}
          </Button>
        </Space>
      </div>

      {/* 标签表格 */}
      <Table
        columns={columns}
        bordered={true}
        dataSource={tagdata}
        pagination={false}
        rowSelection={rowSelection}
        rowKey={record => record.id}
        style={{ paddingBottom: "1.5rem", minHeight: "590px" }}
      ></Table>
      <AddTag
        open={open}
        close={handleClose}
        editok={handleEditTag}
        addok={handleAddTag}
        dialog={dialog}
        tagdata={dialog === "EditTag" ? currentTag : undefined}
      />
    </div>
  );
};

export default LabelPage;
